package com.chatsystem.controller;

import com.chatsystem.dto.ApiResponse;
import com.chatsystem.entity.Message;
import com.chatsystem.service.MessageService;
import com.chatsystem.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 * 
 * @author ChatSystem
 * @version 1.0.0
 */
@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class FileController {

    private final MessageService messageService;
    private final UserService userService;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.max-size}")
    private long maxFileSize;

    /**
     * 上传文件
     * 
     * @param file 文件
     * @param receiverId 接收者ID
     * @param username 发送者用户名
     * @return 上传结果
     */
    @PostMapping("/upload")
    public ResponseEntity<ApiResponse<?>> uploadFile(@RequestParam("file") MultipartFile file,
                                                   @RequestParam("receiverId") Long receiverId,
                                                   @RequestParam("username") String username) {
        try {
            // 检查文件大小
            if (file.getSize() > maxFileSize) {
                return ResponseEntity.badRequest().body(ApiResponse.error("文件大小超过1GB限制"));
            }

            // 检查文件是否为空
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("文件不能为空"));
            }

            // 创建上传目录
            String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String fullUploadDir = uploadDir + "/" + dateDir;
            File dir = new File(fullUploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件
            Path filePath = Paths.get(fullUploadDir, uniqueFilename);
            Files.copy(file.getInputStream(), filePath);

            // 生成文件URL
            String fileUrl = "/api/files/download/" + dateDir + "/" + uniqueFilename;

            // 查找发送者
            var senderOpt = userService.findByUsername(username);
            if (senderOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("发送者不存在"));
            }

            var sender = senderOpt.get();

            // 保存消息到数据库
            Message message = messageService.sendMessage(
                sender.getId(),
                receiverId,
                "文件: " + originalFilename,
                Message.MessageType.FILE,
                fileUrl,
                originalFilename,
                file.getSize()
            );

            Map<String, Object> result = new HashMap<>();
            result.put("message", message);
            result.put("fileUrl", fileUrl);
            result.put("fileName", originalFilename);
            result.put("fileSize", file.getSize());

            return ResponseEntity.ok(ApiResponse.success("文件上传成功", result));

        } catch (IOException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("文件上传失败: " + e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 下载文件
     * 
     * @param dateDir 日期目录
     * @param filename 文件名
     * @return 文件
     */
    @GetMapping("/download/{dateDir}/{filename}")
    public ResponseEntity<?> downloadFile(@PathVariable String dateDir, @PathVariable String filename) {
        try {
            Path filePath = Paths.get(uploadDir, dateDir, filename);
            File file = filePath.toFile();

            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 设置响应头
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
                    .body(Files.readAllBytes(filePath));

        } catch (IOException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("文件下载失败: " + e.getMessage()));
        }
    }

    /**
     * 删除文件
     * 
     * @param dateDir 日期目录
     * @param filename 文件名
     * @return 删除结果
     */
    @DeleteMapping("/{dateDir}/{filename}")
    public ResponseEntity<ApiResponse<?>> deleteFile(@PathVariable String dateDir, @PathVariable String filename) {
        try {
            Path filePath = Paths.get(uploadDir, dateDir, filename);
            File file = filePath.toFile();

            if (!file.exists()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("文件不存在"));
            }

            if (Files.deleteIfExists(filePath)) {
                return ResponseEntity.ok(ApiResponse.success("文件删除成功"));
            } else {
                return ResponseEntity.badRequest().body(ApiResponse.error("文件删除失败"));
            }

        } catch (IOException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("文件删除失败: " + e.getMessage()));
        }
    }
} 